/**
 * @Author 韦建韩
 * @Date 2022/5/20
 */
package com.example.devops.service.impl;

import com.example.devops.Manage.InstanceHandleManager;
import com.example.devops.dao.MirrorCreateMapper;
import com.example.devops.dao.ProjectMapper;
import com.example.devops.entity.pojo.MirrorInformation;
import com.example.devops.entity.pojo.Project;
import com.example.devops.exception.CustomException;
import com.example.devops.exception.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class InstanceService {
    Logger log = LoggerFactory.getLogger(InstanceService.class);
    @Autowired
    ProjectMapper projectMapper;
    @Autowired
    MirrorCreateMapper mirrorCreateMapper;


    public void stopInstance(Long id){
        Project project = projectMapper.selectById(id);
        Long mirrorId = project.getMirrorId();
        MirrorInformation mirrorInformation = mirrorCreateMapper.selectById(mirrorId);
        String gitAddr = mirrorInformation.getGitAddr();
        log.info("gitaddr:{}",gitAddr);
        int i1 = gitAddr.lastIndexOf("/")+1;
        String substring1 = gitAddr.substring(i1);
        int i = substring1.indexOf(".git");
        String name = substring1.substring(0, i);
        String port = project.getPort();
        String containerName = name+port;
        log.info("containerName:{}",containerName);
        InstanceHandleManager manager = new InstanceHandleManager("0", containerName);
       try {
           manager.run();
           project.setState("服务已停止");
           projectMapper.updateById(project);
       }catch (Exception e){
           log.error("action script error",e);
           throw new CustomException("调用脚本失败");
       }
    }
    public void deleteInstance(Long id){
        Project project = projectMapper.selectById(id);
        if(!"服务已停止".equals(project.getState())){
            throw new ValidationException("服务正在运行，不可停止");
        }
        Long mirrorId = project.getMirrorId();
        MirrorInformation mirrorInformation = mirrorCreateMapper.selectById(mirrorId);
        String gitAddr = mirrorInformation.getGitAddr();
        int i1 = gitAddr.lastIndexOf("/")+1;
        String substring1 = gitAddr.substring(i1);
        int i = substring1.indexOf(".git");
        String name = substring1.substring(0, i);
        String port = project.getPort();
        String containerName =  name+port;
        InstanceHandleManager manager = new InstanceHandleManager("1", containerName);
        try {
            manager.run();
            projectMapper.deleteById(project.getId());
        }catch (Exception e){
            log.error("action script error",e);
            throw new CustomException("调用脚本失败");
        }
    }
}
